<?php
	// check params size and names
	if (sizeof($_GET) != 3 || !array_key_exists('code', $_GET) || !array_key_exists('appkey', $_GET) || !array_key_exists('hdi', $_GET))
	{
		echo "Usage";
		exit;
	}

	// if passed then define vars and check strlen after trim
	$code = $_GET['code'];
	$appkey = $_GET['appkey'];
	$hdi = $_GET['hdi'];
	if (strlen(trim($code)) != 40 || strlen(trim($appkey)) != 40 || strlen(trim($hdi)) != 40)
	{
		echo "Size!";
		exit;
	}

	// if passed then connect to db
	$mysqli = new mysqli('localhost', 'root', 'project3', 'implauth');
	if ($mysqli->connect_errno)
	{
		echo "db connection error!";
		exit;
	}

	// if passed then check code for validity
	$res = $mysqli->query("select * from accountstbr where code like '$code'");
	if (!$res)
	{
		echo 90;
		$mysqli->close();
		exit;
	}
	if ($res->num_rows != 1)
	{
		echo 1;
		$res->close();
		$mysqli->close();
		exit;
	}
	
	// if passed then extract id and hun and try to update
	$ob = $res->fetch_object();
	$res->close();
	$id = $ob->serverid;
	$hun = $ob->hun;
	$res = $mysqli->query("select * from accounts where serverid like '$id' and hun like '$hun'");
	if (!$res)
	{
		echo 91;
		$mysqli->close();
		exit;
	}
	$ob = $res->fetch_object();
	$res->close();
	$currenthdi = $ob->hdeviceid;
	$currentappkey = $ob->appkey;
	if (strcmp($currenthdi, $hdi) == 0 && strcmp($currentappkey, $appkey) == 0)
	{
		echo "Same Device!";
		$mysqli->close();
		exit;
	}
	$res = $mysqli->query("update hdvid_appkey set hdvid = '$hdi', appkey = '$appkey' where hdvid = '$currenthdi' and appkey = '$currentappkey'");
	if (!$res)
	{
		echo 92;
		$mysqli->close();
		exit;
	}

	// if passed then delete the code
	$mysqli->query("delete from accountstbr where code like '$code'");

	echo 0;
	$mysqli->close();
	exit;
	

	
























?>
